package chat

import (
	"context"
	"github.com/gogf/gf/v2/util/gconv"
	"time"
	"xr-game-server/core/actor"
	"xr-game-server/core/constants/cmd"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/push"
	"xr-game-server/dao/guilddao"
	"xr-game-server/dto/chatdto"

	"xr-game-server/core/httpserver"
	"xr-game-server/dao/roledao"
	"xr-game-server/errercode"
)

var unionHistoryMap = make(map[uint64][]*chatdto.PushChatDto, common.Zero)
var unionActor = actor.NewActor(1000)

func initUnion() {
	unionActor.Start()
}

func UnionChat(ctx context.Context, req *chatdto.UnionChatReq) (bool, error) {
	roleId := httpserver.GetAuthId(ctx)
	cd := chkCD(roleId, Union)
	if cd != nil && time.Now().Before(*cd) {
		return false, errercode.CreateCode(errercode.ChatCD)
	}
	roleData := roledao.GetRoleByRole(roleId)
	if roleData.GuildId == common.Zero {
		return false, errercode.CreateCode(errercode.GuildNonExist)
	}
	pushDto := chatdto.NewPushChatDto(roleData, req.Content, req.Param)
	//读取工会列表发送聊天消息
	members := guilddao.GetGuildMembers(roleData.GuildId)
	for _, val := range members {
		push.Data(val.RoleId, cmd.UnionChat, pushDto)
	}
	flushCD(roleId, Union)
	unionActor.Send(pushDto, func(data any) {
		//需要读取角色
		uRoleId := data.(*chatdto.PushChatDto).ChatObj.RoleId
		unionHistory, _ := unionHistoryMap[gconv.Uint64(uRoleId)]
		unionHistory = append([]*chatdto.PushChatDto{data.(*chatdto.PushChatDto)}, worldHistory...)
		if len(worldHistory) > WorldMax {
			unionHistory = unionHistory[:WorldMax]
		}
	})
	return true, nil
}

func GetUnionChat(ctx context.Context, req *chatdto.GetUnionChatReq) ([]*chatdto.PushChatDto, error) {
	roleId := httpserver.GetAuthId(ctx)
	//读取工会列表
	unionHistory := unionHistoryMap[roleId]
	return unionHistory, nil
}
